package com.ruoyi.project.ledger.controller;

import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.PermissionService;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.project.ledger.domain.LedgerBusinessAccount;
import com.ruoyi.project.ledger.domain.LedgerFirefightingFacilities;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysUser;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.ledger.domain.LedgerFirefightingEquipment;
import com.ruoyi.project.ledger.service.ILedgerFirefightingEquipmentService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 消防设备Controller
 *
 * @author ruoyi
 * @date 2020-05-11
 */
@RestController
@RequestMapping("/ledger/equipment")
public class LedgerFirefightingEquipmentController extends BaseController
{
    @Autowired
    private ILedgerFirefightingEquipmentService ledgerFirefightingEquipmentService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private PermissionService permissionService;

    /**
     * 查询消防设备列表
     */
//    @PreAuthorize("@ss.hasPermi('ledger:equipment:list')")
    @GetMapping("/list")
    public TableDataInfo list(LedgerFirefightingEquipment ledgerFirefightingEquipment)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 场站id
        Long stationId = user.getStationId();
        if(stationId != null){
            ledgerFirefightingEquipment.setStationId(stationId);
        }
        // 管辖区域
        List<String> areaList = user.getAreaList();
        String areas = String.join(",", areaList);
        String managementCharacters = user.getManagementCharacters();
        ledgerFirefightingEquipment.setAreas(areas);
        ledgerFirefightingEquipment.setManagementCharacters(managementCharacters);
        startPage();
        List<LedgerFirefightingEquipment> list = ledgerFirefightingEquipmentService.selectLedgerFirefightingEquipmentList(ledgerFirefightingEquipment);
        return getDataTable(list);
    }

    /**
     * 导出消防设备列表
     */
//    @PreAuthorize("@ss.hasPermi('ledger:equipment:export')")
    @Log(title = "消防设备", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(LedgerFirefightingEquipment ledgerFirefightingEquipment)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 场站id
        Long stationId = user.getStationId();
        if(stationId != null){
            ledgerFirefightingEquipment.setStationId(stationId);
        }
        // 管辖区域
        List<String> areaList = user.getAreaList();
        String areas = String.join(",", areaList);
        String managementCharacters = user.getManagementCharacters();
        ledgerFirefightingEquipment.setAreas(areas);
        ledgerFirefightingEquipment.setManagementCharacters(managementCharacters);
        List<LedgerFirefightingEquipment> list = ledgerFirefightingEquipmentService.selectLedgerFirefightingEquipmentList(ledgerFirefightingEquipment);
        int i=0;
        for (LedgerFirefightingEquipment equipment : list){
            equipment.setId(Long.valueOf(++i));
        }
        ExcelUtil<LedgerFirefightingEquipment> util = new ExcelUtil<LedgerFirefightingEquipment>(LedgerFirefightingEquipment.class);
        return util.exportExcel(list, "消防设备");
    }

    @Log(title = "消防设备", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('ledger:equipment:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        Long stationId = null;
        // 判断是否是场站角色
        if(!permissionService.hasRole("admin") && (permissionService.hasRole("station") || permissionService.hasRole("hs_station"))){
            SysUser user = SecurityUtils.getLoginUser().getUser();
            stationId = user.getStationId();
        }
        else{
            return AjaxResult.error("当前角色无导入权限");
        }
        ExcelUtil<LedgerFirefightingEquipment> util = new ExcelUtil<>(LedgerFirefightingEquipment.class);
        List<LedgerFirefightingEquipment> equipmentList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = ledgerFirefightingEquipmentService.importEquipment(equipmentList, updateSupport, operName,stationId);
        return AjaxResult.success(message);
    }

    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        List<LedgerFirefightingEquipment> list = new ArrayList<>();
        list.add(new LedgerFirefightingEquipment(Long.valueOf(1),"汽修区","方杰超市",2,1,"宽70cm*高160cm","52cm*67cm",1,1,"导入前，请删除例子"));
        list.add(new LedgerFirefightingEquipment(Long.valueOf(2),"加油站","",2,0,"宽70cm*高160cm","52cm*67cm",1,1,"导入前，请删除例子"));
        ExcelUtil<LedgerFirefightingEquipment> util = new ExcelUtil<>(LedgerFirefightingEquipment.class);
        return util.exportExcel(list,"消防设备数据模板");
    }

    /**
     * 获取消防设备详细信息
     */
//    @PreAuthorize("@ss.hasPermi('ledger:equipment:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(ledgerFirefightingEquipmentService.selectLedgerFirefightingEquipmentById(id));
    }

    /**
     * 新增消防设备
     */
    @PreAuthorize("@ss.hasPermi('ledger:equipment:add')")
    @Log(title = "消防设备", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LedgerFirefightingEquipment ledgerFirefightingEquipment)
    {
        // 判断是否是场站角色
        if(!permissionService.hasRole("admin") && (permissionService.hasRole("station") || permissionService.hasRole("hs_station"))){
            SysUser user = SecurityUtils.getLoginUser().getUser();
            Long stationId = user.getStationId();
            ledgerFirefightingEquipment.setStationId(stationId);
            ledgerFirefightingEquipment.setCreateId(String.valueOf(user.getUserId()));
        }
        else{
            return AjaxResult.error("当前角色无新增权限");
        }
        if (UserConstants.NOT_UNIQUE.equals(ledgerFirefightingEquipmentService.checkEquipmentUnique(ledgerFirefightingEquipment)))
        {
            return AjaxResult.error("新增消防设备失败，该消防设备位置:'" + ledgerFirefightingEquipment.getPosition() + "'已存在");
        }
        return toAjax(ledgerFirefightingEquipmentService.insertLedgerFirefightingEquipment(ledgerFirefightingEquipment));
    }

    /**
     * 修改消防设备
     */
    @PreAuthorize("@ss.hasPermi('ledger:equipment:edit')")
    @Log(title = "消防设备", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LedgerFirefightingEquipment ledgerFirefightingEquipment)
    {
        // 判断是否是场站角色
        if(!permissionService.hasRole("admin") && (permissionService.hasRole("station") || permissionService.hasRole("hs_station"))){
            SysUser user = SecurityUtils.getLoginUser().getUser();
            Long stationId = user.getStationId();
            ledgerFirefightingEquipment.setStationId(stationId);
            ledgerFirefightingEquipment.setCreateId(String.valueOf(user.getUserId()));
        }
        else{
            return AjaxResult.error("当前角色无修改权限");
        }
        if (UserConstants.NOT_UNIQUE.equals(ledgerFirefightingEquipmentService.checkEquipmentUnique2(ledgerFirefightingEquipment)))
        {
            return AjaxResult.error("修改消防设备失败，该消防设备位置:'" + ledgerFirefightingEquipment.getPosition() + "'已存在");
        }
        return toAjax(ledgerFirefightingEquipmentService.updateLedgerFirefightingEquipment(ledgerFirefightingEquipment));
    }

    /**
     * 删除消防设备
     */
    @PreAuthorize("@ss.hasPermi('ledger:equipment:remove')")
    @Log(title = "消防设备", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(ledgerFirefightingEquipmentService.deleteLedgerFirefightingEquipmentByIds(ids));
    }
}
